#include <pthread.h>
#include "tcp_socket.hpp"
#define CHECE_ERS(q) if((q)==false){return -1;}


void* entry(void* arg)
{
  TcpSocket* conn_sock=(TcpSocket*)arg;

  while(1)
  {      //新建连接与客户端通信
    std::string buf;
    bool ret;
    ret=conn_sock->Recv(&buf);
    if(ret==false)
    {
      conn_sock->Close();
      break;
    }
    std::cout<<"client say:"<<buf;

    std::cout<<"serve say:";

    fflush(stdout);
    std::cin>>buf;
    ret=conn_sock->Send(buf);
    if(ret==false)
    {
      conn_sock->Close();
      break;
    }
  }
  conn_sock->Close();
  delete conn_sock;
  return NULL;
}

bool new_worker(TcpSocket* conn_sock)
{
  pthread_t tid;
  int ret;
  ret=pthread_create(&tid,NULL,entry,(void*)conn_sock);

  if(ret!=0)
  {
    perror("pthread error");
    return false;
  }
  pthread_detach(tid);
  return true;

}

int main()
{
  TcpSocket list_sock;
  //创建套接字
  CHECE_ERS(list_sock.Socket());
  //绑定地址信息
  CHECE_ERS(list_sock.Bind("192.168.227.143",9000));
  //开始监听
  CHECE_ERS(list_sock.Listen());

  //获取新建链接
  while(1)
  {
    TcpSocket* conn_sock=new TcpSocket();
    std::string cliip;
    std::string cliprot;
    bool ret;
    ret=list_sock.Accept(conn_sock,&cliip,&cliprot);
    if(ret==false)
    {
      continue;
    }

    std::cout<<"new connection"<<cliip<<":"<<cliprot<<std::endl;
    //线程之间共享文件描述符表
    new_worker(conn_sock);
  }



  //关闭套接字
  list_sock.Close();
  return 0;
}






